import os
import shutil
import subprocess
import sys

def clean_previous_builds():
    """清理之前的构建产物"""
    dirs_to_clean = ['build', 'dist', 'D5Core.egg-info']
    for dir_name in dirs_to_clean:
        if os.path.exists(dir_name):
            print(f"清理 {dir_name}")
            shutil.rmtree(dir_name)

def check_dependencies():
    """检查打包依赖是否已安装"""
    required_packages = ['setuptools', 'wheel', 'twine']
    for package in required_packages:
        try:
            __import__(package)
        except ImportError:
            print(f"缺少打包依赖: {package}，正在安装...")
            subprocess.check_call([sys.executable, '-m', 'pip', 'install', package])

def scan_dependencies():
    """扫描项目依赖"""
    print("扫描项目依赖...")
    
    # 检查pipreqs是否已安装
    try:
        subprocess.check_call([sys.executable, '-m', 'pip', 'show', 'pipreqs'], 
                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        pipreqs_installed = True
    except subprocess.CalledProcessError:
        pipreqs_installed = False
    
    # 如果未安装，则先安装pipreqs
    if not pipreqs_installed:
        print("安装pipreqs用于依赖扫描...")
        subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'pipreqs'])
    
    # 使用pipreqs命令行工具而不是直接导入模块
    if not os.path.exists("requirements.txt") or os.path.getsize("requirements.txt") == 0:
        print("正在生成requirements.txt...")
        try:
            subprocess.check_call([sys.executable, '-m', 'pipreqs', '.', '--force'])
            print("已生成requirements.txt")
        except subprocess.CalledProcessError:
            print("警告: pipreqs执行失败，尝试手动创建requirements.txt")
            # 创建一个基本的requirements文件
            with open("requirements.txt", "w") as f:
                f.write("PySide2>=5.15.0\nshiboken2>=5.15.0\n")
            print("已创建基本的requirements.txt")

def update_setup_from_requirements():
    """从requirements.txt更新setup.py中的依赖"""
    if os.path.exists("requirements.txt"):
        print("从requirements.txt更新setup.py中的依赖...")
        try:
            with open("requirements.txt", "r") as f:
                requirements = [line.strip() for line in f if line.strip() and not line.startswith("#")]
            
            # 读取当前setup.py
            with open("setup.py", "r", encoding="utf-8") as f:
                setup_content = f.read()
            
            # 查找install_requires部分
            import re
            pattern = r"install_requires=\[(.*?)\]"
            match = re.search(pattern, setup_content, re.DOTALL)
            
            if match:
                # 格式化新的依赖列表
                formatted_deps = ",\n        ".join([f'"{dep}"' for dep in requirements])
                new_requires = f"install_requires=[\n        {formatted_deps},\n    ]"
                
                # 替换install_requires部分
                new_content = re.sub(pattern, new_requires, setup_content, flags=re.DOTALL)
                
                # 保存更新后的setup.py
                with open("setup.py", "w", encoding="utf-8") as f:
                    f.write(new_content)
                
                print("已更新setup.py中的依赖")
        except Exception as e:
            print(f"更新setup.py依赖时出错: {str(e)}")

def build_package():
    """构建Python包"""
    print("开始构建包...")
    subprocess.check_call([sys.executable, 'setup.py', 'sdist', 'bdist_wheel'])
    print("构建完成")

def main():
    """主函数"""
    print("=== D5Core打包脚本 ===")
    
    # 确保工作目录是项目根目录
    script_dir = os.path.dirname(os.path.abspath(__file__))
    os.chdir(script_dir)
    
    # 清理之前的构建
    clean_previous_builds()
    
    # 检查打包依赖
    check_dependencies()
    
    # 扫描项目依赖
    scan_dependencies()
    
    # 从requirements.txt更新setup.py
    update_setup_from_requirements()
    
    # 构建包
    build_package()
    
    print("\n打包完成! 生成的包位于dist目录")
    print("可使用以下命令安装:")
    

    print(f"{sys.executable} -m pip uninstall D5Core -y")
    
    print(f"{sys.executable} -m pip install --find-links={os.path.join(script_dir, 'dist')} D5Core")
    

if __name__ == "__main__":
    main()
